#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import Blueprint,render_template,request,session,redirect,url_for,flash
from ..database import User
from ..utils import calc_md5
from ..secure import login_required

from sqlalchemy import and_



bp = Blueprint('login', __name__, url_prefix="/login")
@bp.route('/', methods=["POST","GET"])
def login():

    '''视图-登录'''
    in_s = 'user' in session and session['user'] is not None
    if in_s:
        # 如果已经登录了，跳转到首页
        return redirect(url_for('index.index'))
    # 如果是POST请求，才判断是否是要登录
    if request.method == 'POST':

        # 获取请求参数
        req_username = request.values.get('username', None)
        req_password = request.values.get('password', None)
        # 参数检测
        if req_username is not None and req_password is not None:
            # 去掉首尾的空白字符
            _username = req_username.strip()
            _password = req_password.strip()
            if bool(_username):
                if not bool(_password):
                    flash('缺少密码')
                else:
                    # 查询用户信息
                    cursor = User.query.filter(and_(
                        User.name == _username,
                        User.e_password == calc_md5(_password)
                    ))
                    # 判断查询结果条数
                    if cursor.count() > 0:
                        # 取得第一条数据
                        user_obj = cursor.first()
                        # 设置session（注意：session值不能使User对象，需要是Python内置类型）
                        session['user'] = user_obj.to_dict()
                        # 跳转
                        return redirect(url_for('index.index'))
                    else:
                        flash('用户名或密码错误')
                        
            else:
                flash('缺少用户名')
        else:
            flash('缺少参数')
    return render_template('pages/login.html')




